<?php
class EmployeeAction extends CommonAction {
	
	function _initialize(){
        parent::_initialize();
        $this->dao = D('Member');// 编辑、删除操作需要
    }
	
	
	
	
	function index(){
		$this->listmap="1";
		$this->getLevelNameList = $this->dao -> getLevelNameList();
		if($this->_get('keywords')){
			$this->listmap .= " and (nickname like '%".$this->_get('keywords')."%' or id = '".$this->_get('keywords')."')";
			$this->keywords = $this->_get('keywords');
		}
		
		if($this->_get('level')){
			if($this->_get('level') != 'all'){
				$this->listmap .= " and (level = '".$this->_get('level')."')";
			}
			
			$this->level = $this->_get('level');
		}  
        
        if($this->_get('groupid')){
           $this->listmap.=" and group_id!= 0  ";
        }
		$this->listmap.=" and site_id=".$this->siteid. '  ';//and pid = 0 
        parent::_list();
		/*$list = $this->get('list');
		foreach($list as $k => $v){
		    //$list[$k]['sub'] = $this -> dao -> getListToArray1($v['id'], $this->siteid);
			$list[$k]['level'] = $this->dao->getLevelName($v['id']);
		}
		$this->assign('list', $list);*/
		$map['site_id'] = $this->siteid;
		$coupons = M('coupon')->where($map)->select();
		$this->assign("coupons",$coupons);
		$this->display();
	}
		public function sendCoupon(){
		$coupon_id = $this->_post('coupon_id');
		$this->ids = explode(',', $this->_post('ids'));
		$need = count($this->ids);
		import("@.ORG.Coupon.Coupon");
        $Coupon = new Coupon($coupon_id,"0");
        if($Coupon->canUse()){
        	$exist = $Coupon->exist();
        	if($need <= $exist){
        		$ret['status'] = 1;
        		$ret['info'] = null;
        		foreach($this->ids as $openid){
        			$member_map['openid'] = $openid;
        			$member_map['site_id'] = $this->siteid;
        			$member = M('member')->where($member_map)->find();
        			if($member && $result = $Coupon->getCoupon($member['id'])){
        				$msg = "赠送您一张".$Coupon->coupon['title']."优惠券，价值".
        				$Coupon->coupon['discount']."元，在商城买满".$Coupon->coupon['full']."可以使用，有效期为".
        				$Coupon->coupon['sn_expires']."天";
        				sendWXMsg($openid,$msg);
        			}else{
        				$ret['status'] = 0;
        				$ret['info'] .= "赠送用户ID为".$openid."优惠券时发生错误，赠送该用户失败<br>";
        			}
        		}
        		$ret['info'] = $ret['info'] ? $ret['info'] : "发放成功";
        	}else{
        		$ret['status'] = 0;
        		$ret['info'] = "发放数量超出优惠券数量";
        	}
        }
        echo json_encode($ret);

	    //显示发送页面
		// if($this->_post('ids')){
		// 	$this->ids = explode(',', $this->_post('ids'));
		// 	$count = 0;
		// 	foreach($this->ids as $v){
		// 		if(sendWXMsg($v, $this->_post('msg'))){
		// 			$count ++;
		// 		}
		// 	}
		// 	$ret['status'] = 1;
		// 	$ret['info'] = $count;
		// 	$ret['data'] = '';
		// 	echo json_encode($ret);
		// }
	}
	private function getMember(){
		$pid = $this->_post('id') ? $this->_post('id') : $_GET['id'];
		$map['m.pid'] = $pid;
		$map['m.site_id'] = $this->siteid;
		$ret = array();
		$list = $this->dao -> where($map) ->alias('m') -> select();
		foreach($list as $k => $v){
			//查找层级
			$deep = M('Member_member') -> where(array('member_id' => $_GET['id'],'smember_id' => $v['id'])) -> getField('deep');
			$sub = $this -> dao -> where(array('pid' => $v['id'])) -> count();
			$isParent = false;
			if($sub > 0){
				$isParent = true;
			}
			$data['isParent'] = $isParent;
			$data['id'] = $v['id'];
			$data['name'] = 'ID:'.$v['id'].'　'.$v['nickname'].'　('.$v['username'].')【'.(1 + $deep).'级会员有'.$sub.'个子级】';
			$ret[] = $data;
		}
		echo json_encode($ret);
	}
	public function membertree(){
		if(IS_POST){
			$this->getMember();
			exit;
		}
		$this->display();
	}
	//查看下级会员
	 function sindex(){
		$map = 'mm.member_id = '.$this->_get('id');
		$this->id = $this->_get('id');
		$this->getLevelNameList = $this->dao -> getLevelNameList();
		if($this->_get('keywords')){
			$map .= " and (m.nickname like '%".$this->_get('keywords')."%' or m.id = '".$this->_get('keywords')."')";
			$this->keywords = $this->_get('keywords');
		}
		
		if($this->_get('level')){
			if($this->_get('level') != 'all'){
				$map .= " and (mm.level = '".$this->_get('level')."')";
			}
			
			$this->level = $this->_get('level');
		}  
		
		
		$this->initView();
		$db = D('Member_member'); 
		$db -> _list($this->view, $map);
		
		$this->display();
	}
	//编辑会员
	public function edit(){
		//$this->group_list=M('Member_group')->where(array('site_id'=>$this->siteid))->select();
		$this->getLevelNameList = $this->dao -> getLevelNameList();
		//$this->role_list=M('Member_group')->alias('r')->join('left join __MEMBER_ROLE_USER__ ru ON r.id=ru.role_id and ru.user_id='.$this->_get('id')) -> where(array('r.user_id' => session(C('USER_AUTH_KEY')))) -> select();
		$this->position_list=D('Member_position')->getList(['site_id'=>$this->siteid]);
        $this->role_list=D('Member_group')-> getList2(0,0,array('site_id'=>$this->siteid));
		
		
		
		$member_role_user = M('Member_role_user')-> where(array('user_id' => $this->_get('id'))) -> select();

		foreach($member_role_user as $k => $v){
			
			$member_role_userid[] = $v['role_id'];
		}
		$this->member_role_userids = $member_role_userid;
		//dump($this->member_role_userids);
		
		
        $this->rule_list=D('Integral_rule')->alias('r')->join('left join __INTEGRAL_RULETYPE__ t on r.type_id = t.id')->where(array('r.site_id'=>__SITEID__,'t.isfix'=>1))->Field('r.*')->select();
		$this->supplierList=M('Supplier')->alias('s')->join('left join __MEMBER_SUPPLIER__ ms ON s.id=ms.supplier_id and ms.member_id='.$this->_get('id')) -> where(array('s.site_id' => $this->siteid)) -> Field('s.*,ms.member_id,ms.supplier_id') -> select();
		parent::edit();
		addDetection('Member');
		addDetection('Admin');
	}
	//新建会员
	public function add(){
		$this->getLevelNameList = $this->dao -> getLevelNameList();
        $this->role_list=D('Member_group')-> getList2(0,0,array('site_id'=>$this->siteid));
        $this->rule_list=D('Integral_rule')->alias('r')->join('left join __INTEGRAL_RULETYPE__ t on r.type_id = t.id')->where(array('r.site_id'=>__SITEID__,'t.isfix'=>1))->Field('r.*')->select();
		parent::add();
	}
	//更新用户信息
	public function update(){
		$member_id = $this->_post('id');
		if($this -> _post('leveldown') == 0){
			M('Member_member') -> where(array('smember_id' => $member_id)) -> data(array('level' => $this->_post('level'))) -> save();
			
		}
        if(trim($_POST['role_id'][0])!=''){$_POST['group_id']=$_POST['role_id'][0];}
		if($member_id){
            if(""!=trim($_POST['password'])){
                $_POST['password']=md5($_POST['password']);    
            }else{
                unset($_POST['password']);
            }
            if(isset($_POST['reg_time'])){$_POST['reg_time']=strtotime($_POST['reg_time']);}
            if(isset($_POST['rule_id'])){$_POST['rule_id']=implode(',',$_POST['rule_id']);}
			if(isset($_POST['role_id'])){
				$data1=$_POST;
				//dump($data);exit(); 
				$role_user=M('Member_role_user');
				$role_user->where(array('user_id'=>$data1['id']))->delete();
				foreach($data1['role_id'] as $k=>$v){
					$r['user_id']=$data1['id'];
					$r['role_id']=$v;
					if(!$role_user->add($r)){
						$flag=false;
					}
				}
			}
            
		    $db = D('member_supplier'); 
			$db -> where(array('member_id' => $member_id, 'site_id' => $this->siteid)) -> delete();
			//重新写入
			foreach($_POST['supplier_id'] as $k => $v){
				$data['supplier_id'] = $v;
				$data['member_id'] = $member_id;
				$data['site_id'] = $this->siteid;
				$db -> add($data);
			}
            
		}
		addDetection('Member');
		addDetection('Admin');
		parent::update();
	}
    public function insert(){
		if($jumpUrl == ''){
			$jumpUrl = (session('jumpUrl')&&session('jumpUrl')!='') ? session('jumpUrl') : U('Admin/' . MODULE_NAME . '/index');
		}
		if(isset($_POST)){
			if(!session(C('ADMIN_AUTH_KEY') )){
			    $_POST['pid'] = session(C('USER_AUTH_KEY'));
			}
			if(isset($_POST['reg_time'])){$_POST['reg_time']=strtotime($_POST['reg_time']);}
            if(isset($_POST['rule_id'])){$_POST['rule_id']=implode(',',$_POST['rule_id']);}
			$_POST['password']=md5($_POST['password']);
			$createret = $this->dao->create();
			
			if(!$createret){
				$this->error($this->dao -> getError());exit;
			}
			
			$id = $this->dao->add();
			
			if(!$id){
				$this->error($this->dao -> getError());exit;
			}
			$data=$_POST;
			$flag=true;
			$role_user=M('Member_role_user');
            $role_user->where(array('user_id'=>$data['id']))->delete();
			foreach($data['role_id'] as $k=>$v){
				$r['user_id']=$id;
				$r['role_id']=$v;
				if(!$role_user->add($r)){
					$flag=false;
				}
			}
			if($flag){
				$this->success('添加成功',$jumpUrl);
			}else{
				$this->error('出错了,可能是数据库链接出错,请检查');
			}
			//parent::insert();
		}
	}
	public function sendMsg(){
	    //显示发送页面
		if($this->_post('ids')){
			$this->ids = explode(',', $this->_post('ids'));
			$count = 0;
			foreach($this->ids as $v){
				if(sendWXMsg($v, $this->_post('msg'))){
					$count ++;
				}
			}
			$ret['status'] = 1;
			$ret['info'] = $count;
			$ret['data'] = '';
			echo json_encode($ret);
		}
	}
	//更新父ID
	public function updatePid(){
		if($this->_post('pid')){
			$pid = $this->_post('pid');
			$member_id = $this -> _post('member_id');
			$ret = $this->dao -> updatePid($member_id, $pid);
			if($ret){
				$this->success('操作成功！');
			}else{
				$this->error('操作失败，该会员的父ID不能更改');
			}
		}else{
			$this->error('参数错误');
		}
	}
	//更新父ID
	public function deletePid(){
		if($this->_get('pid')){
			$pid = $this->_get('pid');
			$member_id = $this -> _get('member_id');
			$ret = $this->dao -> deletePid($member_id, $pid);
			if($ret){
				
				
				M('Member_member') -> where(array('site_id' => $this->siteid, 'member_id'=>$pid, 'smember_id' => $member_id )) -> delete();
				
				
				$this->success('操作成功！');
			}else{
				$this->error('操作失败，该会员的父ID不能更改');
			}
		}else{
			$this->error('参数错误');
		}
	}
	
	public function delete(){
		if(isset($_GET['id']) && intval($_GET['id'])>0){
			M('Member_member') -> where(array('site_id' => $this->siteid, 'smember_id' => $this->_get('id') )) -> delete();
		}
		parent::delete();
		
	}
	
	//添加会员积分
	public function addintegral(){
		$id = $this->_get('id');

		if(IS_POST){
		   $id = $this->_post('id');
		   $integral = $this->_post('integral');
		   import("@.ORG.Integrals.Integral");
		   $Integral = new Integral($id);
		   $mes = $Integral->giveIntegral($integral);
		   if($mes){
				$this->success('操作成功！');
				exit;
			}else{
				$this->error('操作失败');
				exit;
			}
		}
		
		$this->assign('id',$id);
		$this->display();
	}
	
	//会员直接登录
	public function login(){
		$member = $this->dao -> where(array('site_id' => $this->siteid, 'id' => $this-> _get('id'))) -> find();dump($member);
		session('memberInfo', $member);
		redirect('/'.$this->siteid.U('Member/Index/index'));
	} 
	
	
	
	//选择列表
	public function select(){
		$this->pagesize = 12;
		$this->listmap = "site_id = ". __SITEID__;
		$this->listmap .= " and group_id <> 0 ";
		if($this->_get('selected') && $this->_get('selected') != ''){
			$this->pagesize = 100;
			$this->listmap = "id in(".$this->_get('selected').")";
		}
		if($this->_param('keywords')){
			$keywords=$this->_param('keywords');
			$_GET['keywords']=urlencode($this->_param('keywords'));
			$this->listmap.=" and title like '%{$keywords}%'";
			$this->keywords=$keywords;
		}
		parent::_list();
		
		$list = $_GET['list'];
		$statu=$list?1:0;
		if(IS_AJAX){
			die(json_encode(array('tbody'=>$this->fetch(),'dump'=>$_REQUEST,'statu'=>$statu, 'pages' => $this->get('pages'))));	
		}else{
			$this->display();
		}
	}
}